<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\AccountEnum;
use app\service\token\TokenInterface;
use app\service\token\TokenService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

class RefreshTokenWork extends BaseWork
{
    protected object $service;

    protected function configure()
    {
        // 指令配置
        $this->setName('refresh_token_work');
        $this->setDescription('刷新token');
        $this->addArgument('media_id', Argument::REQUIRED, '媒体id');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $mediaId = intval($input->getArgument('media_id'));
        $output->writeln('=======刷新token开始' . date('Y-m-d H:i:s', time()) . '=======');
        try {
            $service = TokenService::getInstance($mediaId);
            if (! $service instanceof TokenInterface) {
                $output->writeln('=======刷新token失败,服务有误' . date('Y-m-d H:i:s', time()) . '=======');
                return;
            }
            $appTokens = $service->getMediaAppTokens(AccountEnum::PUTTING_STATUS_OK);
            if (! empty($appTokens)) {
                foreach ($appTokens as $val) {
                    $res = $service->refreshToken($val);
                    if (! $res) {
                        $output->writeln('=======刷新token失败,key:' . $val->getAttr('redis_key') . ',' . $service::getError(0) . date('Y-m-d H:i:s', time()) . '=======');
                        continue;
                    }
                    $output->writeln('=======刷新token成功,key:' . $val->getAttr('redis_key') . ',成功' . date('Y-m-d H:i:s', time()) . '=======');
                }
            }
        } catch (\Exception $e) {
            $output->writeln('=======刷新token失败' . $e->getMessage() . date('Y-m-d H:i:s', time()) . '=======');
        }

        $output->writeln('=======刷新token结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }
}
